package com.innovation.client;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.innovation.config.GlobalConfig;
import com.innovation.config.GlobalConfig.ServerConfig;
import com.innovation.data.model.ModelData;
import com.innovation.message.ServerMessageProto.ServerMessage;

/**
 * 客户端连接池(包含多个同步连接和一个异步连接)
 * @author Administrator
 *
 */
public class ClientPool {
	private static final Logger log = Logger.getLogger(ClientPool.class);
	private final int poolSize = 1;//连接池大小
	private BlockingQueue<Client> synClients = new LinkedBlockingQueue<Client>();//同步发送数据的客戶端連接
	private Client asynClient = null; //异步发送数据的客户端连接
	
	
	
	/**
	 * 客户端连接初始化
	 */
	public void init(String host, int port, int bufferSendSize, int bufferRecvSize){
		//初始化同步连接
		for(int i = 0; i < poolSize; i++){
			TcpClient client = new TcpClient(host, port, bufferSendSize, bufferRecvSize);
			client.connect();
			synClients.offer(client);
		}
		
		//初始化异步连接
		asynClient = new TcpClient(host, port, bufferSendSize, bufferRecvSize);
		asynClient.connect();
	}
	
	public ServerMessage sendAndRecv(ServerMessage msg){
		Client client = null;
		try {
			client = synClients.poll(100, TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
			log.error(e);
		}
		
		//连接不够用
		if (client == null) {
	       log.error("no idle client!!!, pool full");
	       return null;
	    }
		try{
			ServerMessage result = client.sendAndRecv(msg);
			return result;
		}finally{
			//归还连接
			synClients.offer(client);
		}
	}
	
	/**
	 * 异步发送数据,不需要等待数据返回
	 * @param msg
	 */
	public void send(ServerMessage msg){
		asynClient.send(msg);
	}
	
	public static void main(String[] args) throws Exception {
		GlobalConfig.init();
		ServerConfig serverConfig = GlobalConfig.getFightServerConfigMap().get(0);
		TcpClient client = new TcpClient(serverConfig.host, serverConfig.socketPort, 2048, 2048);
		client.connect();
		
		//通过FightServer转发消息
		ServerMessage.Builder request = ServerMessage.newBuilder();
		request.setCmdCode(1);
		request.setIsForward(true);
//		GetPlayerReq.Builder body = GetPlayerReq.newBuilder();
//		body.setPlayerId(4);
//		body.setData(ModelData.DATA_ALL);
//		request.setData(body.build().toByteString());
		
		
		Object msg = client.sendAndRecv(request.build());
		ServerMessage response = (ServerMessage)msg;
		System.out.println(response);
		
		client.destroy();
		
	}
}
